/* Formats a file of text */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "line.h"
#include "word.h"

#define MAX_WORD_LEN 20

int main(int argc, char **argv)
{
    FILE *fpin, *fpout;
    char word[MAX_WORD_LEN + 2];
    int word_len;

  if (argc != 3)
  {
      fprintf(stderr, "USAGE: %s input-file output-file\n", argv[0]);
      exit(EXIT_FAILURE);
  }

  if ( ( fpin = fopen(argv[1], "r") ) == NULL )
  {
      fprintf(stderr, "Error: file %s cannot be read\n", argv[1]);
      exit(EXIT_FAILURE);
  }

  if ( ( fpout = fopen(argv[2], "w") ) == NULL )
  {
      fprintf(stderr, "Error: file %s cannot be written\n", argv[2]);
      fclose(fpin);
      exit(EXIT_FAILURE);
  }

    clear_line();
    for (; ; )
    {
        read_word (word, MAX_WORD_LEN + 1, fpin);
        word_len = strlen(word);
        if (word_len == 0)
        {
            flush_line(fpout);
            break;
        }
        if (word_len + 1 > space_remaining() )
        {
            write_line(fpout);
            clear_line();
        }
        add_word (word, fpin, fpout);
    }

  fclose(fpin);
  fclose(fpout);
  
  exit(EXIT_SUCCESS);
}
